<?php
/**
 * OrderMake.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-20
 * Time: 11:25
 */

namespace App\Tables;


use App\Exceptions\RunException;

class OrderMake extends Base
{
    const BASE_NUMBER = 88;

    /**
     * 生成订单号
     * @return mixed
     * @throws \Exception
     */
    public static function make()
    {
        \DB::beginTransaction();
        $id = (int) date('Ymd');
        $find = self::where('id', $id)->lockForUpdate()->first();
        if(empty($find)) {
            $ok = (bool) self::insert(['id' => $id, 'no' => self::BASE_NUMBER]);
        } else {
            $ok = (bool) $find->increment('no');
        }
        if(!$ok) {
            \DB::rollBack();
            throw new RunException('操作失败(om)');
        }
        $no = self::where('id', $id)->value('no');
        \DB::commit();
        return date('ymd').str_pad($no, 4, 0, STR_PAD_LEFT);
    }
}